﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace hello_accinv
{
    public partial class Mainform : Form
    {
        private Database db;
        private decimal actualPrice;
        private decimal salePrice;

        public Mainform()
        {
            InitializeComponent();
            db = new Database();
            if (!db.TestConnection())
            {
                //System.Environment.Exit(1);
            }
        }

        private void btnAddNewProduct_Click(object sender, EventArgs e)
        {
            AddProduct ap = new AddProduct();
            ap.ShowDialog();
            LoadTableProduct();
        }

        private void Mainform_Load(object sender, EventArgs e)
        {
            //if (MessageBox.Show("Recreate database?", "Database", MessageBoxButtons.YesNo) == DialogResult.Yes)
            //{
            //    RecreateDatabase();
            //}
            LoadTableProduct();
            LoadCategoryList();
            dateTimePickerHistoryFrom.MaxDate = DateTime.Today;
            dateTimePickerHistoryTo.MaxDate = DateTime.Today;
            txtboxSalePCode.Focus();
        }

        private void LoadTableProduct()
        {
            datagridProduct.DataSource = 
                db.Select("P.PCode AS PCode, P.Name AS PName, P.PriceB AS PPrice, P.Quantity AS PQuantity, P.Detail AS PDetail, C.Name AS CName, C.Unit AS CUnit",
                          "Product P INNER JOIN Category C ON P.CategoryID = C.CategoryID",
                          "1");
            datagridProduct.ClearSelection();
        }

        private void LoadTableProduct(string condition)
        {
            datagridProduct.DataSource =
                db.Select("P.PCode AS PCode, P.Name AS PName, P.PriceB AS PPrice, P.Quantity AS PQuantity, P.Detail AS PDetail, C.Name AS CName, C.Unit AS CUnit",
                          "Product P INNER JOIN Category C ON P.CategoryID = C.CategoryID",
                          condition);
            datagridProduct.ClearSelection();
        }

        private void btnDeleteProduct_Click(object sender, EventArgs e)
        {
            if (datagridProduct.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow dr in datagridProduct.SelectedRows)
                {
                    if (MessageBox.Show("Code\t" + dr.Cells["PCode"].Value + "\nName\t" + dr.Cells["PName"].Value + "\nCategory\t" + dr.Cells["PCategory"].Value + "\n\nDo you want to delete this product?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    {
                        db.Delete("Product", "PCode = '" + dr.Cells["PCode"].Value + "'");
                    }
                }
                LoadTableProduct();
            }
            datagridProduct.ClearSelection();
        }

        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (datagridProduct.SelectedRows.Count == 0)
            {
                btnEditProduct.Enabled = false;
                btnDeleteProduct.Enabled = false;
            }
            else
            {
                btnEditProduct.Enabled = true;
                btnDeleteProduct.Enabled = true;
            }
        }

        private void cmbCategoryFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCategoryFilter.Enabled && cmbCategoryFilter.SelectedIndex != -1)
            {
                String condition;
                DataTable dt = db.Select("CategoryID", "Category", "Name = '" + cmbCategoryFilter.SelectedItem.ToString() + "'");
                condition = "C.CategoryID = '" + dt.Rows[0]["CategoryID"].ToString() + "'";
                LoadTableProduct(condition);
            }
        }

        private void LoadCategoryList()
        {
            DataTable dt = db.Select("Name", "Category", "1 ORDER BY Name ASC");
            List<string> lst = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                lst.Add(dt.Rows[i]["Name"].ToString());
            }
            cmbCategoryFilter.DataSource = lst;
            cmbSaleCategory.DataSource = lst;
            cmbCategoryFilter.SelectedIndex = -1;
            cmbSaleCategory.SelectedIndex = -1;
        }

        private void radioFilterCategory_CheckedChanged(object sender, EventArgs e)
        {
            cmbCategoryFilter.SelectedIndex = -1;
            if (radioFilterCategory.Checked)
            {
                cmbCategoryFilter.Enabled = true;
            }
            else
            {
                cmbCategoryFilter.Enabled = false;
            }
        }

        private void radioShowAll_CheckedChanged(object sender, EventArgs e)
        {
            if (radioShowAll.Checked)
            {
                LoadTableProduct();
            }
        }

        private void btnEditProduct_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello world");
        }

        private void btnManageCategory_Click(object sender, EventArgs e)
        {
            ManageCategory mc = new ManageCategory();
            mc.ShowDialog();
            LoadCategoryList();
        }

        private void RecreateDatabase()
        {
            MySqlConnection conn = new MySqlConnection("Server=localhost;" +
                                                        "Uid=root;" +
                                                        "Pwd=;" +
                                                        "CharSet=utf8;" +
                                                        "Allow Zero Datetime=True;");
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = conn;
            conn.Open();
            cmd.CommandText = "DROP DATABASE accinv";
            cmd.ExecuteNonQuery();
            cmd.CommandText = "SET NAMES UTF8";
            cmd.ExecuteNonQuery();
            cmd.CommandText = "CREATE DATABASE accinv CHARACTER SET utf8 COLLATE utf8_general_ci";
            cmd.ExecuteNonQuery();
            cmd.CommandText = "USE accinv";
            cmd.ExecuteNonQuery();

            string[] tableList = hello_accinv.Properties.Resources.DML.Split(';');
            foreach (string table in tableList)
            {
                if (!table.Equals(""))
                {
                    cmd.CommandText = table;
                    cmd.ExecuteNonQuery();
                }
            }
        }

        private void btnAddtoStock_Click(object sender, EventArgs e)
        {
            AddStock ads = new AddStock();
            ads.ShowDialog();
            LoadTableProduct();
        }

        private void txtboxSalePCode_TextChanged(object sender, EventArgs e)
        {
            if (txtboxSalePCode.Text.Length == 3)
            {
                if (!IsNumeric(txtboxSalePCode.Text))
                {
                    // Get category name
                    DataTable dt = db.Select("Name", "Category", "Codename = '" + txtboxSalePCode.Text + "'");
                    if (dt.Rows.Count > 0)
                    {
                        txtboxSalePCode.ForeColor = Color.Black;
                        cmbSaleCategory.SelectedItem = dt.Rows[0]["Name"].ToString();
                    }
                    else
                    {
                        txtboxSalePCode.ForeColor = Color.Red;
                    }
                }
                else
                {
                    txtboxSalePCode.ForeColor = Color.Red;
                }
            }
            else if (txtboxSalePCode.Text.Length == 6)
            {
                if (!IsNumeric(txtboxSalePCode.Text.Substring(0, 3)) && IsNumeric(txtboxSalePCode.Text.Substring(3, 3)))
                {
                    // Get product name
                    DataTable dt = db.Select("Name", "Product", "PCode = '" + txtboxSalePCode.Text + "'");
                    if (dt.Rows.Count > 0)
                    {
                        txtboxSalePCode.ForeColor = Color.Blue;
                        // select in table
                        foreach (DataGridViewRow dr in datagridSaleProduct.Rows)
                        {
                            if (dr.Cells["SalePCode"].Value.Equals(txtboxSalePCode.Text))
                            {
                                dr.Selected = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        txtboxSalePCode.ForeColor = Color.Red;
                    }
                }
                else
                {
                    txtboxSalePCode.ForeColor = Color.Red;
                }
            }
            else
            {
                txtboxSalePCode.ForeColor = Color.Black;
                datagridSaleProduct.ClearSelection();
            }
        }

        private bool IsNumeric(string input)
        {
            string validChars = "0123456789.";
            char inputChar;
            bool result = true;
            for (int i = 0; i < input.Length; i++)
            {
                inputChar = input[i];
                if (validChars.IndexOf(inputChar) == -1)
                {
                    result = false;
                    break;
                }
            }
            return result;
        }

        private void cmbSaleCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSaleCategory.SelectedIndex != -1)
            {
                DataTable dt;
                // Get category codename
                dt = db.Select("CategoryID, Codename, Unit", "Category", "Name = '" + cmbSaleCategory.SelectedItem.ToString() + "'");
                txtboxSalePCode.ForeColor = Color.Black;
                txtboxSalePCode.Text = dt.Rows[0]["Codename"].ToString();
                txtboxSalePCode.Focus();
                txtboxSalePCode.SelectionStart = txtboxSalePCode.Text.Length;
                //lbSaleProductUnit.Text = dt.Rows[0]["Unit"].ToString();

                // Get product list
                dt = db.Select("PCode AS SalePCode, Name AS SalePName", "Product", "CategoryID = '" + dt.Rows[0]["CategoryID"].ToString() + "'");
                datagridSaleProduct.DataSource = dt;
                datagridSaleProduct.ClearSelection();
            }
            else
            {
                txtboxSalePCode.Text = "";
                //lbSaleProductUnit.Text = "Unit";
                ClearTableSaleProduct();
            }
        }

        private void ClearTableSaleProduct()
        {
            int rowCount = datagridSaleProduct.Rows.Count;
            for (int i = 0; i < rowCount; i++)
            {
                datagridSaleProduct.Rows.RemoveAt(0);
            }
        }

        private void datagridSaleProduct_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (datagridSaleProduct.SelectedRows.Count > 0)
            {
                txtboxSalePCode.Text = datagridSaleProduct.SelectedRows[0].Cells["SalePCode"].Value.ToString();
            }
        }

        private void datagridSaleProduct_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (datagridSaleProduct.SelectedRows.Count > 0)
            {
                DataTable dt = db.Select("PriceB", "Product", "PCode = '" + datagridSaleProduct.SelectedRows[0].Cells["SalePCode"].Value + "'");
                txtboxSalePrice.Text = dt.Rows[0]["PriceB"].ToString();
                actualPrice = decimal.Parse(dt.Rows[0]["PriceB"].ToString());
                salePrice = actualPrice;
                mtxtboxSaleAmount.Enabled = true;
                mtxtboxSaleAmount.Focus();
                mtxtboxSaleAmount.SelectionStart = 0;
                txtboxDiscountPercent.Enabled = true;
                txtboxDiscountBaht.Enabled = true;
            }
            else
            {
                txtboxDiscountPercent.Enabled = false;
                txtboxDiscountBaht.Enabled = false;
                mtxtboxSaleAmount.Enabled = false;
                txtboxSalePrice.Text = "";
                txtboxSalePCode.Focus();
                txtboxSalePCode.SelectionStart = txtboxSalePCode.Text.Length;
            }
        }

        private void ResetSaleForm()
        {
            txtboxSalePCode.Text = "";
            cmbSaleCategory.SelectedIndex = -1;
            txtboxSalePrice.Text = "";
            mtxtboxSaleAmount.Text = "";
            txtboxDiscountPercent.Text = "%";
            txtboxDiscountBaht.Text = "Baht";
        }

        private void ClearTabSale()
        {
            ResetSaleForm();
            int rowCount = datagridSaleProductList.Rows.Count;
            for (int i = 0; i < rowCount; i++)
            {
                datagridSaleProductList.Rows.RemoveAt(0);
            }
            txtboxSaleTotalPrice.Text = "";
        }

        private void AddSaleProductToList()
        {
            decimal totalPrice = salePrice * decimal.Parse(mtxtboxSaleAmount.Text);
            datagridSaleProductList.Rows.Add(
                new Object[] { 
                    datagridSaleProductList.Rows.Count + 1, 
                    datagridSaleProduct.SelectedRows[0].Cells["SalePName"].Value, 
                    salePrice, 
                    Int32.Parse(mtxtboxSaleAmount.Text), 
                    totalPrice,
                    (salePrice == actualPrice) ? "":("Discounted " + txtboxDiscountBaht.Text)
                }
            );
        }

        private void datagridSaleProductList_Leave(object sender, EventArgs e)
        {
            datagridSaleProductList.ClearSelection();
        }

        public string ToLongBaht(String value)
        {
            string longBaht = "";
            string preBaht = "";
            string postBaht = "";

            string[] th = new String[] { "ล้าน", "แสน", "หมื่น", "พัน", "ร้อย", "สิบ" };
            string[] thaiDigit = new String[] { "ศูนย์", "หนึ่ง", "สอง", "สาม", "สี่", "ห้า", "หก", "เจ็ด", "แปด", "เก้า" };

            string pre, post;
            pre = post = "";
            int ipre, ppre;
            ipre = ppre = 0;

            if (value.Contains("."))
            {
                pre = value.Substring(0, value.IndexOf('.'));
                post = value.Substring(value.IndexOf('.') + 1);
                if (post.Length > 2)
                {
                    Console.WriteLine("สตางค์ไม่ถูก");
                    return "";
                }
                ipre = Int32.Parse(pre);
                ppre = Int32.Parse(post);
            }
            else
            {
                pre = value;
                ipre = Int32.Parse(pre);
            }

            // บาท
            int start = 6;
            int mod = 10;
            for (int i = 0; i < (pre.Length); i++)
            {
                int index = (ipre % mod) / (mod / 10);
                if (i != 0)
                {
                    if ((index == 2) && (start == 6))
                    {
                        preBaht = "ยี่" + th[start - 1] + preBaht;
                    }
                    else if ((index == 1) && (start == 6))
                    {
                        preBaht = th[start - 1] + preBaht;
                    }
                    else if (index != 0)
                    {
                        preBaht = thaiDigit[index] + th[start - 1] + preBaht;
                    }
                    start--;
                    mod *= 10;
                }
                else
                {
                    if ((index == 1) && (ipre > 10))
                        preBaht = "เอ็ด" + preBaht;
                    else if (index != 0)
                        preBaht = thaiDigit[index] + preBaht;
                    mod *= 10;
                }
            }

            // สตางค์
            start = 6;
            mod = 10;
            for (int i = 0; i < (post.Length); i++)
            {
                int index = (ppre % mod) / (mod / 10);
                if (i != 0)
                {
                    if ((index == 2) && (start == 6))
                    {
                        postBaht = "ยี่" + th[start - 1] + postBaht;
                    }
                    else if ((index == 1) && (start == 6))
                    {
                        postBaht = th[start - 1] + postBaht;
                    }
                    else if (index != 0)
                    {
                        postBaht = thaiDigit[index] + th[start - 1] + postBaht;
                    }
                    start--;
                    mod *= 10;
                }
                else
                {
                    if ((index == 1) && (ppre > 10))
                        postBaht = "เอ็ด" + postBaht;
                    else if (index != 0)
                        postBaht = thaiDigit[index] + postBaht;
                    mod *= 10;
                }
            }

            if (pre.Length > 0)
                longBaht += preBaht + "บาท";
            if ((post.Length > 0) && (ppre > 0))
                longBaht += postBaht + "สตางค์";
            else
                longBaht += "ถ้วน";

            return longBaht;
        }

        private void txtboxSalePCode_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F1:
                    txtboxSalePCode.SelectAll();
                    break;
                case Keys.F2:
                    if (datagridSaleProduct.SelectedRows.Count > 0)
                    {
                        txtboxDiscountPercent.Focus();
                        txtboxDiscountPercent.SelectAll();
                    }
                    break;
                case Keys.F3:
                    if (datagridSaleProduct.SelectedRows.Count > 0)
                    {
                        mtxtboxSaleAmount.Focus();
                        mtxtboxSaleAmount.SelectAll();
                    }
                    break;
                case Keys.F4:
                case Keys.F5:
                    if (datagridSaleProductList.Rows.Count > 0)
                    {
                        txtboxSaleCashAmount.Focus();
                        txtboxSaleCashAmount.SelectAll();
                    }
                    break;
                case Keys.Enter:
                    if (datagridSaleProduct.SelectedRows.Count > 0)
                    {
                        mtxtboxSaleAmount.Focus();
                        mtxtboxSaleAmount.SelectAll();
                    }
                    break;
            }
        }

        private void mtxtboxSaleAmount_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (mtxtboxSaleAmount.Text.Length > 0 && mtxtboxSaleAmount.ForeColor == Color.Black)
                    {
                        AddSaleProductToList();
                        ResetSaleForm();
                    }
                    break;
                case Keys.Escape:
                    ResetSaleForm();
                    break;
                case Keys.F1:
                    txtboxSalePCode.Focus();
                    txtboxSalePCode.SelectAll();
                    break;
                case Keys.F2:
                    txtboxDiscountPercent.Focus();
                    txtboxDiscountPercent.SelectAll();
                    break;
                case Keys.F3:
                    mtxtboxSaleAmount.SelectAll();
                    break;
                case Keys.F4:
                case Keys.F5:
                    txtboxSaleCashAmount.Focus();
                    txtboxSaleCashAmount.SelectAll();
                    break;
            }
        }

        private void mtxtboxSaleAmount_TextChanged(object sender, EventArgs e)
        {
            if (mtxtboxSaleAmount.Text.Length > 0)
            {
                if (!IsNumeric(mtxtboxSaleAmount.Text) || Int32.Parse(mtxtboxSaleAmount.Text) == 0)
                {
                    mtxtboxSaleAmount.ForeColor = Color.Red;
                }
                else
                {
                    mtxtboxSaleAmount.ForeColor = Color.Black;
                    mtxtboxSaleAmount.Text = Int32.Parse(mtxtboxSaleAmount.Text).ToString();
                    mtxtboxSaleAmount.SelectionStart = mtxtboxSaleAmount.Text.Length;
                }
            }
        }

        private void datagridSaleProductList_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (datagridSaleProductList.Rows.Count > 0)
            {
                decimal sum = 0;
                foreach (DataGridViewRow dr in datagridSaleProductList.Rows)
                {
                    sum += decimal.Parse(dr.Cells["SalePLTotalPrice"].Value.ToString());
                }
                txtboxSaleTotalPrice.Text = sum.ToString("0,0.00");
                lbLongbaht.Text = ToLongBaht(sum.ToString());
                txtboxSaleCashAmount.Enabled = true;
            }
            else
            {
                txtboxSaleTotalPrice.Text = "";
                lbLongbaht.Text = "";
                txtboxSaleCashAmount.Text = "";
                txtboxSaleCashAmount.Enabled = false;
            }
            txtboxSaleNumOfItems.Text = datagridSaleProduct.Rows.Count.ToString();
        }

        private void datagridSaleProductList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 6)
            {
                string pname = datagridSaleProductList.Rows[e.RowIndex].Cells["SalePLName"].Value.ToString();
                if (MessageBox.Show("Delete " + pname, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    datagridSaleProductList.Rows.RemoveAt(e.RowIndex);
                }
                txtboxSalePCode.Focus();
            }
        }

        private void Mainform_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (datagridSaleProductList.Rows.Count > 0)
            {
                if (MessageBox.Show("In progress, Cancel?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
        }

        private void radioHistorySelectedDate_CheckedChanged(object sender, EventArgs e)
        {
            if (radioHistorySelectedDate.Checked)
            {
                dateTimePickerHistoryFrom.Enabled = true;
                dateTimePickerHistoryTo.Enabled = true;
            }
            else
            {
                dateTimePickerHistoryFrom.Enabled = false;
                dateTimePickerHistoryTo.Enabled = false;
            }
        }

        private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
        {
            switch (e.TabPageIndex)
            {
                case 0:
                    txtboxSalePCode.Focus();
                    break;

                case 1:
                    if (datagridSaleProductList.Rows.Count > 0)
                    {
                        if (MessageBox.Show("In progress, Cancel?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                        {
                            ClearTabSale();
                        }
                        else
                        {
                            e.Cancel = true;
                            txtboxSalePCode.Focus();
                        }
                    }
                    else
                    {
                        ClearTabSale();
                    }
                    cmbCategoryFilter.SelectedIndex = -1;
                    datagridProduct.ClearSelection();
                    break;
            }
        }

        private void txtboxDiscountPercent_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    mtxtboxSaleAmount.Focus();
                    mtxtboxSaleAmount.SelectAll();
                    break;
                case Keys.F1:
                    txtboxSalePCode.Focus();
                    txtboxSalePCode.SelectAll();
                    break;
                case Keys.F2:
                    txtboxDiscountBaht.Focus();
                    txtboxDiscountBaht.SelectAll();
                    break;
                case Keys.F3:
                    mtxtboxSaleAmount.Focus();
                    mtxtboxSaleAmount.SelectAll();
                    break;
                case Keys.F4:
                case Keys.F5:
                    if (datagridSaleProduct.SelectedRows.Count > 0)
                    {
                        if (MessageBox.Show("Cancel current product ?", "?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            txtboxSaleCashAmount.Focus();
                            txtboxSaleCashAmount.SelectAll();
                        }
                    }
                    break;
            }
        }

        private void txtboxDiscountBaht_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    mtxtboxSaleAmount.Focus();
                    mtxtboxSaleAmount.SelectAll();
                    break;
                case Keys.F1:
                    txtboxSalePCode.Focus();
                    txtboxSalePCode.SelectAll();
                    break;
                case Keys.F2:
                    txtboxDiscountPercent.Focus();
                    txtboxDiscountPercent.SelectAll();
                    break;
                case Keys.F3:
                    mtxtboxSaleAmount.Focus();
                    mtxtboxSaleAmount.SelectAll();
                    break;
                case Keys.F4:
                case Keys.F5:
                    if (datagridSaleProduct.SelectedRows.Count > 0)
                    {
                        if (MessageBox.Show("Cancel current product ?", "?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            txtboxSaleCashAmount.Focus();
                            txtboxSaleCashAmount.SelectAll();
                        }
                    }
                    break;
            }
        }

        private void txtboxDiscountPercent_TextChanged(object sender, EventArgs e)
        {
            if (txtboxDiscountPercent.Focused)
            {
                if (!txtboxDiscountPercent.Text.Equals("%") && 
                    !txtboxDiscountPercent.Text.Equals("0") && 
                    txtboxDiscountPercent.Text.Length > 0)
                {
                    if (IsNumeric(txtboxDiscountPercent.Text))
                    {
                        txtboxDiscountPercent.ForeColor = Color.Orange;
                        txtboxDiscountBaht.Text = (((decimal.Parse(txtboxDiscountPercent.Text) / 100) * actualPrice)).ToString("#,#.00");
                        if (decimal.Parse(txtboxDiscountBaht.Text) > actualPrice)
                        {
                            txtboxDiscountPercent.ForeColor = Color.Red;
                            txtboxDiscountBaht.ForeColor = Color.Red;
                        }
                        else
                        {
                            txtboxDiscountPercent.ForeColor = Color.Orange;
                            txtboxDiscountBaht.ForeColor = Color.Orange;
                        }
                    }
                    else
                    {
                        txtboxDiscountPercent.ForeColor = Color.Red;
                    }
                }
                else
                {
                    txtboxDiscountBaht.Text = "Baht";
                }
            }
        }

        private void mtxtboxSaleAmount_Enter(object sender, EventArgs e)
        {
            if (!txtboxDiscountPercent.Text.Equals("%") || !txtboxDiscountBaht.Text.Equals("Baht"))
            {
                if (IsNumeric(txtboxDiscountPercent.Text) && 
                    IsNumeric(txtboxDiscountBaht.Text) && 
                    decimal.Parse(txtboxDiscountBaht.Text) < actualPrice)
                {
                    // Calculate discounted price
                    decimal newPrice = actualPrice - decimal.Parse(txtboxDiscountBaht.Text);
                    txtboxSalePrice.Text = actualPrice + " => " + newPrice.ToString();
                    salePrice = newPrice;

                    txtboxDiscountPercent.Text += " %";
                    txtboxDiscountBaht.Text += " Baht";
                }
                else
                {
                    MessageBox.Show("Wrong discount");
                    txtboxDiscountPercent.ForeColor = Color.Orange;
                    txtboxDiscountBaht.ForeColor = Color.Orange;
                    txtboxDiscountPercent.Text = "%";
                    txtboxDiscountBaht.Text = "Baht";
                    txtboxSalePrice.Text = actualPrice.ToString();
                }
            }
            else
            {
                txtboxDiscountPercent.Text = "%";
                txtboxDiscountBaht.Text = "Baht";
                txtboxSalePrice.Text = actualPrice.ToString();
            }
        }

        private void txtboxDiscountBaht_TextChanged(object sender, EventArgs e)
        {
            if (txtboxDiscountBaht.Focused)
            {
                if (!txtboxDiscountBaht.Text.Equals("Baht") && txtboxDiscountBaht.Text.Length > 0)
                {
                    if (IsNumeric(txtboxDiscountBaht.Text))
                    {
                        txtboxDiscountBaht.ForeColor = Color.Orange;
                        txtboxDiscountPercent.Text = ((int)((decimal.Parse(txtboxDiscountBaht.Text) / actualPrice) * 100)).ToString();
                        if (Int32.Parse(txtboxDiscountPercent.Text) > 100)
                        {
                            txtboxDiscountPercent.ForeColor = Color.Red;
                            txtboxDiscountBaht.ForeColor = Color.Red;
                        }
                        else
                        {
                            txtboxDiscountPercent.ForeColor = Color.Orange;
                            txtboxDiscountBaht.ForeColor = Color.Orange;
                        }
                    }
                    else
                    {
                        txtboxDiscountBaht.ForeColor = Color.Red;
                    }
                }
                else
                {
                    txtboxDiscountPercent.Text = "%";
                }
            }
        }

        private void btnCancelSale_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Cancel all?", "?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ClearTabSale();
                txtboxSalePCode.Focus();
            }
        }

        private void AcceptSale()
        {
            MessageBox.Show("Accept Sale");
        }

        private void tabControl1_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F1:
                    txtboxSalePCode.Focus();
                    break;
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("WTF!");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Discount dc = new Discount();
            dc.textBox1.Text = textBox4.Text;
            if (dc.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox9.Text = dc.textBox3.Text;
            }
            else
            {
                textBox9.Text = "";
            }
        }
    }
}
